package com.niuke.linkedlist;

/**
 * 反转链表
 *
 * @author luhd
 * @date 2023-11-17
 */
public class Bm1 {

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        ListNode listNode = reverseListNode(listNode1);
    }

    /**
     * 反转链表
     *
     * @param head 链表头节点
     * @return 反转后的链表
     */
    public static ListNode reverseListNode(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = null;
        ListNode next = null;
        /**
         * 1.保存当前节点之后的节点
         * 2.将当前节点的下一节点指向排序过的节点，例如1指向null，2指向1，3指向{2，1}
         * 3.即head为当前排序好的节点，将排序好的节点赋值给pre
         * 4.next赋值给head，继续往后遍历
         */
        while(head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

     public static class ListNode {
       int val;
       ListNode next = null;
       public ListNode(int val) {
         this.val = val;
       }
     }
}